package com.summer.boss.auth;

import com.summer.boss.constant.CommonConstants;
import com.summer.boss.model.vo.MenuVO;
import com.summer.boss.utils.JsonUtil;
import com.summer.boss.utils.RedisUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PermissionService {

    public boolean check(String permissionCode) {

        // 1. 获取用户信息,认证成功才能取到
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        JwtInfo jwtInfo = (JwtInfo)auth.getPrincipal();

        // 2. 获取用户权限
        Set<String> userPermissions = getPermissions(jwtInfo.getUsername());
        // 如果配置了权限，校验权限
        if (StringUtils.hasText(permissionCode)) {
            return userPermissions.contains(permissionCode);
        }

        return true;
    }

    private Set<String> getPermissions(String username) {
        // 从缓存或数据库获取用户权限
        String key = String.format(CommonConstants.USER_PERMISSION, username);
        String permission = RedisUtil.get(key);
        Set<MenuVO> menus = JsonUtil.parseSet(permission, MenuVO.class);
        return CollectionUtils.isEmpty(menus) ? Collections.emptySet() : menus.stream().map(MenuVO::getCode).collect(Collectors.toSet());
    }
}
